"""格子达检测平台实现"""

from typing import Optional, Dict, Any

from app.models.enums import DetectionStatus, DetectionPlatform
from app.models.response import TextDetectionResponse
from app.utils.exceptions import PlatformAPIException
from .base import BaseDetectionPlatform


class GezidaDetectionPlatform(BaseDetectionPlatform):
    """格子达检测平台"""
    
    def __init__(self, api_url: str, api_key: str):
        super().__init__(api_url, api_key, DetectionPlatform.GEZIDA)
    
    async def submit_detection(self, text: str, title: Optional[str] = None, 
                             author: Optional[str] = None) -> TextDetectionResponse:
        """提交格子达检测任务"""
        try:
            self.logger.info("提交格子达检测任务")
            
            # 验证文本
            if not self._validate_text_for_platform(text):
                raise PlatformAPIException(
                    self.platform_name.value, 
                    "文本不符合格子达检测要求"
                )
            
            # 准备请求数据
            data = {
                "content": text,
                "title": title or "未命名文档",
                "author": author or "匿名",
                "check_type": "fast",  # 格子达快速检测
                "exclude_refs": True,  # 排除参考文献
                "word_limit": len(text)
            }
            
            # 发送API请求
            response = await self._make_api_request("POST", "/check/submit", data)
            
            # 处理响应
            task_id = response.get("order_id") or response.get("task_id")
            if not task_id:
                raise PlatformAPIException(
                    self.platform_name.value, 
                    "未获取到任务ID"
                )
            
            return self._create_response(
                task_id=task_id,
                status=DetectionStatus.PENDING
            )
            
        except PlatformAPIException:
            raise
        except Exception as e:
            self.logger.error(f"格子达检测任务提交失败: {e}")
            raise PlatformAPIException(
                self.platform_name.value, 
                f"任务提交失败: {str(e)}"
            )
    
    async def get_detection_result(self, task_id: str) -> TextDetectionResponse:
        """获取格子达检测结果"""
        try:
            self.logger.info(f"获取格子达检测结果: {task_id}")
            
            # 发送查询请求
            response = await self._make_api_request("GET", f"/check/result/{task_id}")
            
            # 解析响应
            status_map = {
                "waiting": DetectionStatus.PENDING,
                "checking": DetectionStatus.PROCESSING,
                "finished": DetectionStatus.COMPLETED,
                "error": DetectionStatus.FAILED
            }
            
            status = status_map.get(
                response.get("status", "waiting"), 
                DetectionStatus.PENDING
            )
            
            similarity_rate = response.get("rate")
            if similarity_rate is not None:
                similarity_rate = float(similarity_rate) / 100  # 转换为小数
            
            report_url = response.get("report_url") or response.get("pdf_url")
            
            return self._create_response(
                task_id=task_id,
                status=status,
                similarity_rate=similarity_rate,
                report_url=report_url
            )
            
        except Exception as e:
            self.logger.error(f"获取格子达检测结果失败: {e}")
            raise PlatformAPIException(
                self.platform_name.value, 
                f"获取结果失败: {str(e)}"
            )
    
    async def cancel_detection(self, task_id: str) -> bool:
        """取消格子达检测任务"""
        try:
            self.logger.info(f"取消格子达检测任务: {task_id}")
            
            response = await self._make_api_request("POST", f"/check/cancel/{task_id}")
            
            return response.get("success", False)
            
        except Exception as e:
            self.logger.error(f"取消格子达检测任务失败: {e}")
            return False
    
    def _platform_specific_validation(self, text: str) -> bool:
        """格子达平台特定验证"""
        # 格子达要求最少50字
        if len(text.strip()) < 50:
            return False
        
        # 格子达单次检测最大100万字
        if len(text.strip()) > 1000000:
            return False
        
        return True
    
    def _get_platform_features(self) -> list[str]:
        """获取格子达平台特性"""
        return [
            "学术论文检测",
            "毕业论文检测",
            "期刊投稿检测",
            "职称评审检测",
            "快速检测模式",
            "精准检测模式",
            "支持多种文档格式",
            "实时检测进度",
            "详细相似度分析"
        ]
    
    async def get_account_info(self) -> Dict[str, Any]:
        """获取账户信息（格子达特有功能）"""
        try:
            self.logger.info("获取格子达账户信息")
            
            response = await self._make_api_request("GET", "/account/info")
            
            return {
                "balance": response.get("balance", 0),
                "used_words": response.get("used_words", 0),
                "remaining_words": response.get("remaining_words", 0),
                "vip_level": response.get("vip_level", "普通用户"),
                "expire_date": response.get("expire_date")
            }
            
        except Exception as e:
            self.logger.error(f"获取账户信息失败: {e}")
            return {}
    
    async def get_detection_statistics(self, start_date: str, end_date: str) -> Dict[str, Any]:
        """获取检测统计（格子达特有功能）"""
        try:
            self.logger.info(f"获取检测统计: {start_date} - {end_date}")
            
            data = {
                "start_date": start_date,
                "end_date": end_date
            }
            
            response = await self._make_api_request("POST", "/stats/detection", data)
            
            return {
                "total_detections": response.get("total_count", 0),
                "total_words": response.get("total_words", 0),
                "average_similarity": response.get("avg_similarity", 0),
                "detection_by_day": response.get("daily_stats", [])
            }
            
        except Exception as e:
            self.logger.error(f"获取检测统计失败: {e}")
            return {} 